package com.terra.ns.imp.common.dingtalk.event

import cn.hutool.extra.spring.SpringUtil
import com.alibaba.fastjson2.JSONObject
import com.dingtalk.open.app.api.OpenDingTalkStreamClientBuilder
import com.dingtalk.open.app.api.security.AuthClientCredential
import com.dingtalk.open.app.stream.protocol.event.EventAckStatus
import com.terra.ns.imp.common.dingtalk.client.DingtalkClient
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.context.event.EventListener
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Component

/**
@author qins
@date 2023/9/19
@desc
 */
@Component
class DingStreamEventListener {

    private val log = LoggerFactory.getLogger(this::class.java)

    @Autowired
    private lateinit var dingTalkClient: DingtalkClient

    @EventListener(ApplicationReadyEvent::class)
    @Async
    fun execute() {
        OpenDingTalkStreamClientBuilder.custom()
            .credential(AuthClientCredential(dingTalkClient.getDingtalkConf().appKey, dingTalkClient.getDingtalkConf().appSecret))
            .registerAllEventListener {event ->
                SpringUtil.publishEvent(DingtalkEvent(event.eventId, event.eventType, event.eventCorpId,
                    event.eventBornTime,
                    JSONObject.parse(event.data.toJSONString()),
                     DingStreamEventListener::class.java)
                )
//                DingtalkEventIdCache.add(eventId)
                EventAckStatus.SUCCESS
            }.build().start()
    }

}